package com.heima.comment.service.impl;

import com.heima.comment.client.UserClient;
import com.heima.comment.dto.CommentRepayDto;
import com.heima.comment.dto.CommentRepayLikeDto;
import com.heima.comment.dto.CommentRepaySaveDto;
import com.heima.comment.entity.ApComment;
import com.heima.comment.entity.ApCommentRepay;
import com.heima.comment.entity.ApCommentRepayLike;
import com.heima.comment.entity.ApUser;
import com.heima.comment.service.ICommentRepayService;
import com.heima.comment.vo.ApCommentRepayVo;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.dto.ResponseResult;
import com.heima.common.entity.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocal;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CommentRepayServiceImpl implements ICommentRepayService {
    @Autowired
    private GreenTextScan textScan;
    @Autowired
    private UserClient userClient;
    @Autowired
    private MongoTemplate template;

    /**
     * 回复评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult save(CommentRepaySaveDto dto) {
//        评论不能超过140
        if (dto == null || StringUtils.isEmpty(dto.getContent()) || dto.getContent().length() > 140){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//        判断是否登录
        User user = AppThreadLocal.get();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

//        阿里云判断内容是否合规
        try {
            Map map = textScan.greenTextScan(dto.getContent());
            Object suggestion = map.get("suggestion");
            if (!suggestion.equals("pass")){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        ApCommentRepay commentRepay = new ApCommentRepay();
        commentRepay.setAuthorId(user.getUserId());
        ResponseResult<ApUser> responseResult = userClient.getById(user.getUserId());
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
            ApUser apUser = responseResult.getData();
           commentRepay.setAuthorName(apUser.getName());
        }
        commentRepay.setCommentId(dto.getCommentId());
        commentRepay.setContent(dto.getContent());
        commentRepay.setLikes(0);
        commentRepay.setCreatedTime(new Date());
        template.save(commentRepay);

//        更新评论数
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(dto.getCommentId()));
        Update update = new Update();
        update.inc("reply");
        template.updateFirst(query,update, ApComment.class);

        return ResponseResult.okResult();
    }

    /**
     * 回复评论点赞
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentRepayLikeDto dto) {
        ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
        apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());

        apCommentRepayLike.setOperation(dto.getOperation());
//        判断是否登录
        User user = AppThreadLocal.get();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        apCommentRepayLike.setAuthorId(user.getUserId());
//        查询是否存在
        Query query = new Query();
        query.addCriteria(Criteria.where("authorId").is(user.getUserId()));
        query.addCriteria(Criteria.where("commentRepayId").is(dto.getCommentRepayId()));

        ApCommentRepayLike one = template.findOne(query, ApCommentRepayLike.class);
        int count = 0;
        if (one == null){
            if (dto.getOperation() == 0){
                template.save(apCommentRepayLike);
                count = 1;
            }
        }else {
           if (dto.getOperation() != one.getOperation()){
               one.setOperation(dto.getOperation());
               template.save(one);
               if (dto.getOperation() == 0){
                   count = 1;
               }else {
                   count = -1;
               }
           }
        }
//        修改点赞数
        if (count != 0){
            Query query1 = new Query();
            query1.addCriteria(Criteria.where("id").is(dto.getCommentRepayId()));

            Update update  =new Update();
            update.inc("likes",count);
            template.updateFirst(query1 , update,ApCommentRepay.class);
        }

        return ResponseResult.okResult();
    }

    /**
     * 回复评论分页列表查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(CommentRepayDto dto) {
//        分页查询
        Query query = new Query();
        query.addCriteria(Criteria.where("commentId").is(dto.getCommentId()));
        query.addCriteria(Criteria.where("createdTime").lt(dto.getMinDate()));
        Pageable page = PageRequest.of(0,10, Sort.Direction.DESC,"createdTime");
        query.with(page);
        List<ApCommentRepay> apCommentRepays = template.find(query, ApCommentRepay.class);

        List<ApCommentRepayVo> vos = new ArrayList<>();
        List<String> commentRepayId =  new ArrayList<>();
        for (ApCommentRepay apCommentRepay : apCommentRepays) {
            ApCommentRepayVo vo = new ApCommentRepayVo();
            BeanUtils.copyProperties(apCommentRepay,vo);
            vo.setOperation(1);
            vos.add(vo);

            commentRepayId.add(apCommentRepay.getId());
        }
//        判断用户是否登录
        User user = AppThreadLocal.get();
        if (user == null){
            return ResponseResult.okResult(vos);
        }

        Query likeQuery = new Query();
        likeQuery.addCriteria(Criteria.where("authorId").is(user.getUserId()));
        likeQuery.addCriteria(Criteria.where("commentRepayId").in(commentRepayId));
        List<ApCommentRepayLike> apCommentRepayLikes = template.find(likeQuery, ApCommentRepayLike.class);
        List<String> apCommentRepayPass = new ArrayList<>();
        for (ApCommentRepayLike apCommentRepayLike : apCommentRepayLikes) {
            if (apCommentRepayLike.getOperation() == 0){
                apCommentRepayPass.add(apCommentRepayLike.getCommentRepayId());
            }
        }

        for (ApCommentRepayVo vo : vos) {
            if (apCommentRepayPass.contains(vo.getCommentId())){
                vo.setOperation(0);
            }
        }


        return ResponseResult.okResult(vos);
    }
}
